package com.ciwong.epaper.modules.reciteWords.ui;

import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.guidedialog.BaseGuideLayerDialog;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.msg.util.MsgDateFormat;
import com.ciwong.epaper.modules.reciteWords.bean.JiaoCaiDetailBean;
import com.ciwong.epaper.modules.reciteWords.bean.MakePlanSuccessBean;
import com.ciwong.epaper.modules.reciteWords.dao.WordDao;
import com.ciwong.epaper.modules.reciteWords.ui.fragment.MyTimeWheelViewFrament;
import com.ciwong.epaper.modules.reciteWords.util.WordJumpManager;
import com.ciwong.epaper.modules.reciteWords.util.WordUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.widget.WordPlanNumberView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

/**
 * Created by keepon on 2018/9/11.
 */
public class MakeWordPlanActivity extends BaseActivity implements View.OnClickListener {
	private FrameLayout mFlContainer;
	private TextView    mTvCompleteTime;
	private TextView    mTvCount, mTvBookName;
	private WordPlanNumberView mOneDayNumberWordPlanNumberView, mDayCountWordPlanNumberView;
	JiaoCaiDetailBean mJiaoCaiDetailBean;
	int               mCompleteCount;
	boolean           mIsLearnAgain;
	private Button mBtnSure;
	//天数
	private int    mDays;
	//每天单词个数
	private int    mDayCount;

	@Override
	protected int setView() {
		return R.layout.activity_make_word_plan;
	}

	@Override
	protected void findViews() {
		mFlContainer = findViewById(R.id.fl_container);
		mTvCompleteTime = findViewById(R.id.tv_complete_time);
		mTvCount = findViewById(R.id.tv_count);
		mTvBookName = findViewById(R.id.tv_book_name);
		mDayCountWordPlanNumberView = findViewById(R.id.word_plan_days);
		mOneDayNumberWordPlanNumberView = findViewById(R.id.word_plan_days_count);
		mBtnSure = findViewById(R.id.btn_sure);
		final CardView cardView = findViewById(R.id.card_view_2);
		boolean isShowHelp = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_MAKE_WORD_PLAN + BaseApplication.getInstance().getUserInfoBase().getUserId(), true);
		if (isShowHelp) {
			cardView.post(new Runnable() {
				@Override
				public void run() {
					int height = cardView.getHeight();
					float y = cardView.getY() + (height*3 / 7) + getResources().getDimension(R.dimen.dp_45) -getResources().getDimension(R.dimen.dp_210);
					initGuide((int) y);
				}
			});
		}


	}

	BaseGuideLayerDialog dialog;

	private void initGuide(int height) {
		try {
			if (dialog != null && dialog.isShowing()) {
				return;
			}
			if (dialog == null)
				dialog = new BaseGuideLayerDialog(MakeWordPlanActivity.this, R.style.DialogStyleGuide);
			View view = LayoutInflater.from(MakeWordPlanActivity.this).inflate(R.layout.dialog_make_word_book_tips, null);
			TextView tvDayCount = view.findViewById(R.id.tv_day_cout);
			TextView tvDays = view.findViewById(R.id.tv_days);
			if(mDayCount>0){
				tvDayCount.setText(mDayCount+"个");
			}
			if(mDays>0){
				 tvDays.setText(mDays+"天");
			}
			RelativeLayout relativeLayout = view.findViewById(R.id.rl_tips);
			if (height > 0) {
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();
				if (layoutParams != null){
					layoutParams.topMargin=height;
					if (android.os.Build.MODEL.equalsIgnoreCase("MI 8")) {
						if (layoutParams != null) {
							layoutParams.topMargin = layoutParams.topMargin- getResources().getDimensionPixelSize(R.dimen.dp_26);
						}
					}
				}
			}
			dialog.setContentView(view);
			dialog.setCancelable(false);
			dialog.findViewById(R.id.tx_perusal_know).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_MAKE_WORD_PLAN + BaseApplication.getInstance().getUserInfoBase().getUserId(), false);
					dialog.dismiss();
					dialog = null;

				}
			});
			dialog.show();
		}catch (Exception e ){

		}


	}

	@Override
	protected void initEvent() {
		Intent intent = getIntent();
		if (intent != null) {
			mJiaoCaiDetailBean = (JiaoCaiDetailBean) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_JIAOCAI_DETAIL);
			mCompleteCount = intent.getIntExtra(IntentFlag.INTENT_FLAG_COMPLETE_COUNT, 0);
			mIsLearnAgain = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_WORD_LEARN_AGAIN, false);
		}
		if (mJiaoCaiDetailBean != null) {
			mTvCount.setText(mJiaoCaiDetailBean.getWordsCount() + "");
			mTvBookName.setText(mJiaoCaiDetailBean.getVersionFullName());
		}
		mBtnSure.setOnClickListener(this);
	}

	@Override
	protected void init() {
		setTitleText("制定计划");
	}

	@Override
	protected void loadData() {
		Bundle bundle = new Bundle();
		if (mJiaoCaiDetailBean != null) {
			bundle.putInt(IntentFlag.INTENT_FLAG_TOTAL_NUM, mJiaoCaiDetailBean.getWordsCount() - mCompleteCount);

		}
		MyTimeWheelViewFrament myTimeWheelViewFrament = MyTimeWheelViewFrament.newInstance(bundle);
		FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
		fragmentTransaction.add(R.id.fl_container, myTimeWheelViewFrament);
		fragmentTransaction.commit();
		myTimeWheelViewFrament.setOnDaySelectedListener(new MyTimeWheelViewFrament.onDaySelectedListener() {
			@Override
			public void onDaySeleted(int days, int dayWordNumber) {

				mDays = days;
				mDayCount = dayWordNumber;

				String time = MsgDateFormat.formatDate2(days);
				mTvCompleteTime.setText(time);

				mDayCountWordPlanNumberView.setCount(days);
				mOneDayNumberWordPlanNumberView.setCount(dayWordNumber);
			}
		});
	}

	@Override
	public void onClick(View v) {
		if (!NetworkUtils.isOnline()) {
			ToastUtil.INSTANCE.toastCenterNoNetError();
			return;
		}
		if (!DoubleClickCheckUtils.vertify500Duration()) {
			return;
		}
		int id = v.getId();
		if (id == R.id.btn_sure) {
			showCricleProgress();
			final int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
			if (mIsLearnAgain) {

			} else {

			}
			savePlan(userId);
		}
	}

	private void savePlan(int userId) {
		WordDao.saveAndGetWordPlan(userId, mJiaoCaiDetailBean.getVersionId(), mJiaoCaiDetailBean.getVersionFullName(), mDayCount, mDays, new BaseExtCallBack(MakeWordPlanActivity.this) {
			@Override
			public void failed(int errorCode, Object data) {
				hideCricleProgress();
				super.failed(errorCode, data);
				ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(R.string.server_error, errorCode);
			}

			@Override
			public void failed(Object data) {
				hideCricleProgress();
				super.failed(data);
				if (!NetworkUtils.isOnline()) {
					ToastUtil.INSTANCE.toastCenterNoNetError();
				} else if (data instanceof TimeoutError) {
					ToastUtil.INSTANCE.toastCenterError("连接超时，请稍后重试");
				}
			}

			@Override
			public void success(Object data) {
				hideCricleProgress();
				CWSys.setSharedInt(ListenSpeakUtil.getCurrentPlanBookIdKey(), mJiaoCaiDetailBean.getVersionId());
				//创建计划或者切换计划删除学习记录
				WordUtil.clearStudyRecord();
				WordJumpManager.jumpToWordPlanActivity(R.string.go_back, IntentValue.JumpWordPlanType.FROM_CHANGE_PLAN, null, MakeWordPlanActivity.this);
				EventBus.getDefault().post(new MakePlanSuccessBean(true));
				finish();
			}
		});
	}


}
